const express = require("express");
// const multer=require("multer");
const { db } = require("../database");
// const { getPayloadByToken } = require("../jwt");

// 创建路由对象，使得用户登录状态检查的中间件只作用于部分路由。
const router = express.Router();
const { useAuthorization } = require("./base");
router.use(useAuthorization);

// 创建用户登录状态检查的中间件
// router.use(async (req, res, next) => {
//   // 从请求头部获得 token
//   const { token } = req.headers;
//   const payload = getPayloadByToken(token);
//   // 获取用户id
//   const userId = payload?.userId || req.session?.userId;
//   // 通过 session.userId 判断用户是否登录
//   if (!userId) {
//     return res.status(401).send({ success: false, message: "用户尚未登录!" });
//   }
//   // 为以后获取用户信息方便，将用户信息保存在 req.user 上。
//   req.user = await db.findOne`select * from user where id = ${userId}`;
//   next();
// });
// const storage = multer.diskStorage({
//     destination: function (req, file, cb) {
//       cb(null, "./public/avatars");
//     },
//     filename: function (req, file, cb) {
//       const ext = path.extname(file.originalname);
//       cb(null, uuid() + ext);
//     },
//   });
// const upload=multer({storage});

//查询机构
router.get("/check", async (req, res) => {
    const check = await db.select`select * from organization`;
    res.send({
        code: 200,
        success: true,
        result: check,
    })
});

//组织管理模块增设机构
router.post("/",
    async (req, res) => {
        const { name, sn, description, parent, children } = req.body;
        const org = await db.findOne(`select * from organization where name=?`, [name]);
        if (org) {
            res.send({
                code: -1,
                success: false,
                message: "该机构已存在"
            })
        } else {
            const sql = await db.insert(
                `insert into organization(name,sn,description,parent,children) values(?,?,?,?,?)`,
                [name, sn, description, parent, children]
            );
            const organization = await db.findOne`select * from organization where id=${sql}`;
            res.send({
                code: 200,
                success: true,
                result: organization,
            });
        }
    })

//变更机构人力用例
router.put("/change",
    async (req, res) => {
        const { id } = req.body;
        const change = await db.findOne`select * from organization where id=${id}`;
        if (!change) {
            return res.send({
                code: -1,
                success: false,
                message: "该机构不存在",
            })
        } else {
            const { name, sn, description, parent, children } = req.body;
            await db.run`update organization set name=${name},sn=${sn},description=${description} , parent=${parent},children=${children} where id=${id}`;
            const people = await db.findOne`select * from organization where id=${id}`
            res.send({
                code: 200,
                success: true,
                result: people,
            })
        }
    })

//撤销机构用例
router.delete("/delete",
    async (req, res) => {
        const { id } = req.body
        const change =
            await db.findOne`select * from organization where id=${id}`;
        if (!change) {
            return res.send({
                code: -1,
                success: false,
                message: "该机构不存在",
            })
        } else {
            await db.run`delete from organization where id=${id}`;
            res.send({
                code: 200,
                success: true,
                message: '删除成功',
            });
        }
    })

// 将路由作为中间件挂接在 / 根路由上。
const registerRouter = (app) => app.use("/organization", router);

module.exports = { registerRouter };